package com.company.module.net;

import com.company.module.net.factory.GsonConverterFactory;
import com.company.module.net.factory.StringConverterFactory;
import com.company.module.net.interceptor.changeRequest.ChangeRequestUrlInterceptor;
import com.company.module.net.interceptor.HeaderSetInterceptor;
import com.company.module.net.utils.LogUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * desc : 网络请求工具类
 * user : sixbing
 * time : 2019-03-27 11:30.
 * version : 1.0
 */
public class RetrofitUtil {
    private static RetrofitUtil instance;
    private Retrofit retrofit;
    private OkHttpClient client;
    private static String TAG = "RetrofitUtil";

    public static RetrofitUtil getInstance() {
        if (instance == null) {
            synchronized (RetrofitUtil.class) {
                if (instance == null) {
                    instance = new RetrofitUtil();
                }
            }
        }
        return instance;
    }

    private RetrofitUtil() {
        //Interceptor 拦截器按顺序执行的，先设置header，切换url，打印信息
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(new HeaderSetInterceptor());
        //测试版才打印
        if (BuildConfig.DEBUG) {
            //http请求信息及返回信息打印
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    //打印信息
                    LogUtil.e(TAG, message);
                }
            });
            //设置打印的内容等级
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //动态切换 url 多url请求   通过注解的形式在 api加 @headers 注解 无此需求可不添加拦截器
            ChangeRequestUrlInterceptor urlInterceptor = new ChangeRequestUrlInterceptor();
            //设置要切换的请求链接，只会替换 IP 地址。
            urlInterceptor.putDomain(HttpValues.BASE_URL_LOCAL_key, HttpValues.BASE_URL_LOCAL);
            builder.addInterceptor(urlInterceptor)
                    .addInterceptor(httpLoggingInterceptor);
        }
        client = builder.readTimeout(15, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS)
                .build();
        retrofit = new Retrofit
                .Builder()
                .client(client)
                .baseUrl(HttpValues.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .build();
    }

    /**
     * 添加代理
     *
     * @param <T> 1
     * @return 1
     */
    public <T> T getHttpApi(Class<T> tClass) {
        return retrofit.create(tClass);
    }
}
